package com.dyz.swagger;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

import static com.dyz.contant.Constants.TOKEN_HEADER;

@Configuration
@EnableSwagger2
public class SwaggerAutoConfig {
    @Resource
    private SwaggerProperties swaggerProperties;
    @Bean
    public Docket docket() {
        return  new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())//介绍接口的一些信息
                .select()
                .apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage()))
                .paths(PathSelectors.any())
                .build().securityContexts(securityContexts())//安全的上下文
                .securitySchemes(securitySchemes());//安全的类型

    }

    private List< SecurityScheme> securitySchemes() {
        return Arrays.asList(new ApiKey(TOKEN_HEADER, TOKEN_HEADER, TOKEN_HEADER));
    }

    private List<SecurityContext> securityContexts() {
        return Arrays.asList(new SecurityContext(
                Arrays.asList(new SecurityReference(TOKEN_HEADER,new AuthorizationScope[]{new AuthorizationScope("global", "accessResource")})),
                PathSelectors.any()
        ));
    }

    private ApiInfo apiInfo() {
       return  new ApiInfoBuilder().contact(
                new Contact(swaggerProperties.getContactName(), swaggerProperties.getContactUrl(), swaggerProperties.getContactEmail())
        ).title(swaggerProperties.getTitle())
                .description(swaggerProperties.getDescription())
                .version(swaggerProperties.getVersion())
                .termsOfServiceUrl(swaggerProperties.getTermsOfServiceUrl())
                .build();
    }
}
